# encoding=utf8
import requests
import Utils
import time
import json
import hashlib
import random
import commands
import configparser
import os
import re
import sys
import threading
reload(sys)
sys.setdefaultencoding( "utf-8" )

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
}

def Sessionrequests(getorpost,Session,url,params,data):
    while True:  # 一直循环，知道访问站点成功
        if getorpost =="get":
            try:
                # 以下except都是用来捕获当requests请求出现异常时，
                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                response = Session.get(url, params=params, timeout=20)
                break
            except requests.exceptions.ConnectionError:
                print('ConnectionError -- please wait 3 seconds')
                time.sleep(3)
                ChangeIp()
            except requests.exceptions.ChunkedEncodingError:
                print('ChunkedEncodingError -- please wait 3 seconds')
                time.sleep(3)
                ChangeIp()
            except:
                print('Unfortunitely -- An Unknow Error Happened, Please wait 3 seconds')
                time.sleep(3)
                ChangeIp()
        else:
            try:
                response = Session.post(url, params=params,data=data, timeout=20)
                break
            except requests.exceptions.ConnectionError:
                print('ConnectionError -- please wait 3 seconds')
                time.sleep(3)
                ChangeIp()
            except requests.exceptions.ChunkedEncodingError:
                print('ChunkedEncodingError -- please wait 3 seconds')
                time.sleep(3)
                ChangeIp()
            except:
                print('Unfortunitely -- An Unknow Error Happened, Please wait 3 seconds')
                time.sleep(3)
                ChangeIp()
    return response



def McbbsSingn(session):
    singnparams = {
        'id': 'dc_signin:sign',
        'infloat': 'yes',
        'handlekey': 'sign',
        'inajax': '1',
        'ajaxtarget': 'fwin_content_sign'
    }
    response = Sessionrequests('get', session, 'https://www.mcbbs.net/plugin.php', singnparams, None)
    hashcode = Utils.getHash(response.text)
    jsonlate = GetGeetest(session)
    startparams = {
        'id': 'dc_signin:sign',
        'inajax': '1'
    }
    sendnum = random.randint(0, 5)
    SingnMsg = ['记上一笔，hold住我的快乐！', '格式化自己，只为删除那些不愉快！', '平平淡淡才是真', '我前途无亮啊！！', '人生太多无奈，今天的事让我真是傻眼呀！',
                '人生太多事，今天就在这里大哭一次，希望在明天！']

    print(str(sendnum))
    print(SingnMsg[sendnum])

    SingnData = {
        'formhash': hashcode,
        'signsubmit': 'yes',
        'handlekey': 'signin',
        'emotid': str(sendnum + 1),
        'referer': 'https://www.mcbbs.net/plugin.php?id=dc_signin',
        'action': 'qdlist',
        'content': SingnMsg[sendnum],
        'geetest_challenge': jsonlate['data']['challenge'],
        'geetest_validate': jsonlate['data']['validate'],
        'geetest_seccode': jsonlate['data']['validate'] + '%7Cjordan',
    }
    response = Sessionrequests('post', session, 'https://www.mcbbs.net/plugin.php', startparams, SingnData)
    print(response.text)
    if response.text.find("方验证按钮")!=-1:
        print("已出问题重登陆")
        McbbsSingn(session)

def LoginMcbbs(username, password):
    loginparmas = {
        'mod': 'logging',
        'action': 'login',
        'infloat': 'yes',
        'handlekey': 'login',
        'inajax': '1',
        'ajaxtarget': 'fwin_content_login'
    }
    session = requests.session()
    temptext = Sessionrequests('get', session, 'https://www.mcbbs.net/member.php', loginparmas, None)
    idhash = Utils.getHash(temptext.text)
    loginid = Utils.layer_login_(temptext.text)
    jsonobjlate = GetGeetest(session)
    print(jsonobjlate)
    joinparmas = {
        'mod': 'logging',
        'action': 'login',
        'loginsubmit': 'yes',
        'handlekey': 'login',
        'loginhash': loginid,
        'inajax': '1',
    }

    postmsg = {
        'formhash': idhash,
        'referer': 'https://www.mcbbs.net/thread-565057-1-1.html',
        'username': username,
        'password': password,
        'questionid': '0',
        'geetest_challenge': jsonobjlate['data']['challenge'],
        'geetest_validate': jsonobjlate['data']['validate'],
        'geetest_seccode': jsonobjlate['data']['validate'] + '%7Cjordan'
    }
    test = Sessionrequests('post', session, 'https://www.mcbbs.net/member.php', joinparmas, postmsg)
    print(test.text)
    if test.text.find("方验证按钮")!=-1:
        print("出问题已经重登陆")
        LoginMcbbs(username, password)
    return session


def TaskDo(session):
    Taskparams = {
        'mod': 'task'
    }
    response = Sessionrequests('get', session, 'https://www.mcbbs.net/home.php', Taskparams, None)
    taskhash = Utils.getHash(response.text)
    # 周活跃任务
    Taskparams = {
        'mod': 'task',
        'do': 'apply',
        'id': '23',
        'hash': taskhash
    }
    Sessionrequests('get', session, 'https://www.mcbbs.net/home.php', Taskparams, None)
    Taskparams = {
        'mod': 'task',
        'do': 'draw',
        'id': '23',
        'hash': taskhash
    }
    Sessionrequests('get', session, 'https://www.mcbbs.net/home.php', Taskparams, None)


def GetGeetest(session):
    count = 0
    inflag = 0
    while (inflag == 0):
        count += 1
        geetestparmas = {
            'id': 'geetest3',
            'model': 'start',
            't': str(time.time())
        }
        response = Sessionrequests('get', session, 'https://www.mcbbs.net/plugin.php', params=geetestparmas, data=None)
        jsonobj = json.loads(response.text)

        challengecodeparmas = {
            'gt': jsonobj['gt'],
            'challenge': jsonobj['challenge'],
            'referer': 'https://www.mcbbs.net/thread-565057-1-1.html',
            'secretkey': '.',
            'devCode': '900ec168b8ae4b57997e2e681508b4ce',
            'wtype': 'geetest'
        }
        temptext = Sessionrequests('get', session, 'http://api.ddocr.com/api/gateway.jsonp', challengecodeparmas, None)
        print(str(count) + "正在识别验证")
        # print(temptext.text)
        if len(temptext.text) > 100:
            jsonobj = json.loads(temptext.text)
            print(jsonobj['data']['challenge'])
            print(jsonobj['data']['validate'])
            return jsonobj
        if count == 20:
            exit()


def md5(str):
    m = hashlib.md5()
    m.update(str.encode("utf8"))
    print(m.hexdigest())
    return m.hexdigest()


def SingnUsrall():
    Utils.confusion('./password.txt')
    with open('./password.txt') as f:
        for line in f.readlines():
            print("延迟中")
            time.sleep(random.randint(55,110))
            ChangeIp()
            textpassword = line.split('----')
            user = textpassword[0]
            print(user)
            #password = textpassword[0].replace('@outlook.com', '')+'asd123456'
            password = textpassword[1]
            print(password)
            session = LoginMcbbs(user, password)
            McbbsSingn(session)
            TaskDo(session)
            #BuyCradAndUpTid(session, 921560)

def UpTidAndSingn():
    conf = configparser.ConfigParser()
    conf.read('./config.ini')
    count = conf.getint('conf', 'count')
    tid = conf.get('conf', 'tid')
    if count >= 5:
        conf.set('conf', 'count', str(1))
    else:
        conf.set('conf', 'count', str(count + 1))
    conf.write(open( './config.ini', 'w'))
    print('当前的账号次数:' + str(count))
    lines = []
    with open('./password.txt') as f:
        for line in f.readlines():
            lines.append(line)
            if lines.__len__() == 5:
                break
    for i in range(0, 5):
        textpassword = lines[i].split('----')
        user = textpassword[0]
        print(user)
        password = textpassword[0].replace('@21cn.com', '')
        print(password)
        session = LoginMcbbs(user, password)
        McbbsSingn(session)
        TaskDo(session)
        #BuyCradAndUpTid(session, tid)
        if (i + 1) == count:
            print("当前提升:" + user)
            BuyCradAndUpTid(session, tid)
            # to do


def BuyCradAndUpTid(session, Tid):
    pageparams = {
        'mod': 'magic',
        'action': 'shop'
    }
    response = Sessionrequests('get',session,'https://www.mcbbs.net/home.php', params=pageparams, data=None)
    # print(response.text)
    idhash = Utils.getHash(response.text)
    print(idhash)
    buyparams = {
        'mod': 'magic',
        'action': 'shop',
        'infloat': 'yes',
        'inajax': '1'
    }
    buydata = {
        'formhash': idhash,
        'handlekey': 'magics',
        'operation': 'buy',
        'mid': 'bump',
        'magicnum': '1',
        'operatesubmit': 'yes'
    }
    response = Sessionrequests('post', session, 'https://www.mcbbs.net/home.php', params=buyparams, data=buydata)
    print(response.text)
    UpTidParams = {
        'mod': 'magic',
        'action': 'mybox',
        'infloat': 'yes',
        'inajax': '1'
    }
    UpTidData = {
        'formhash': idhash,
        'handlekey': 'a_bump',
        'operation': 'use',
        'magicid': '16',
        'tid': Tid,
        'usesubmit': 'yes',
        'idtype': 'tid',
        'id': Tid
    }
    Sessionrequests('post', session, 'https://www.mcbbs.net/home.php', params=UpTidParams, data=UpTidData)


def ChangeIp():
    print("Ip 正在更换")
    os.system("/sbin/ifdown ppp0")
    os.system("/sbin/ifup ppp0")
    # global ip
    hostip = commands.getstatusoutput("curl icanhazip.com")[1].split('\n')[-1]
    print(hostip)
    flag = re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", hostip)
    while not flag:
        print("Ip 正在更换")
        print("出问题中")
        os.system("/sbin/ifdown ppp0")
        os.system("/sbin/ifup ppp0")
        # global ip
        hostip = commands.getstatusoutput("curl icanhazip.com")[1].split('\n')[-1]
        flag = re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", hostip)
        print(hostip)



if __name__ == '__main__':
    t1 = threading.Thread(target=SingnUsrall())
    t1.start()
    # UpTidAndSingn()
    # print(ChangeIp("gege"))


